<template>
  <div class="app-container home">
    <el-row :gutter="20">
      <el-card style="margin-bottom: 20px;">
        <div slot="header" class="clearfix">
          <h3>欢迎您：{{ user.userName }}</h3>
        </div>
        <el-col :span="12" class="item">
          <p>当前时间：{{ currentTime }}</p>
        </el-col>
        <el-col :span="12" class="text-right">
          <p v-if="weather && weather.forecast && weather.forecast[0]">今日天气：{{
              weather.forecast[0].type
            }}，{{ weather.forecast[0].high }}，{{ weather.forecast[0].low }}，{{ weather.forecast[0].notice }}</p>
          <p v-else>天气数据加载中...</p>
        </el-col>
        <el-col :span="12" class="text-right">
          <p></p>
        </el-col>
        <el-col :span="12" class="text-right">
          <p></p>
        </el-col>
      </el-card>
    </el-row>
    <el-row :gutter="20">
      <el-card style="margin-bottom: 20px;">
        <el-col :xs="24" :sm="24" :md="12" :lg="8" style="padding-left: 20px">
          <div class="text-center">
            <user-avatar/>
          </div>
          <div class="text-center">
            <p><i class=""></i>
              <svg-icon icon-class="user"/>
              用户名称{{ user.userName }}
            </p>
            <p>
              <svg-icon icon-class="peoples"/>
              所属角色:{{ roleGroup }}
            </p>
          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="8" style="padding-left: 20px">
          <div class="details">
            <p>认证状态：
              <el-tag :type="getTagType(status)">{{ status }}</el-tag>
            </p>
            <p>认证时间：2024-8-16</p>
            <p>企业名称：dlvtc</p>
            <p>联系人手机号：{{ user.phonenumber }}</p>
            <p>组织机构代码：100001</p>
          </div>
        </el-col>
      </el-card>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="6" v-for="(item, index) in statisticsItems" :key="index" style="margin-bottom: 20px;">
        <el-card shadow="hover" :body-style="{ padding: '0px' }">
          <div class="text-container">
            <div class="icon-text">
              <i :class="['el-icon', item.icon]" class="icon"></i>
              <p class="title">{{ item.title }}</p>
            </div>
          </div>
          <div style="text-align: center">
            <p class="value">{{ item.value }}</p>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="15" :lg="15" style="padding-left: 20px">
        <el-card style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <h3>粉丝增长数</h3>
          </div>
          <div id="fansCharts" style="width: 100%; height: 450px;"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="9" :lg="9" style="padding-left: 20px">
        <el-card style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <h3>受众群体</h3>
          </div>
          <div id="bodyCharts" style="width: 100%; height: 450px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import userAvatar from '@/views/system/user/profile/userAvatar.vue'
import userInfo from '@/views/system/user/profile/userInfo.vue'
import { getUserProfile } from '@/api/system/user'
import axios from 'axios'
import * as echarts from 'echarts'
import { listContents_msg } from '@/api/system/contents_msg'
import { listDonations } from '@/api/system/donations'
import { listAds } from '@/api/system/ads'
import { listStats } from '@/api/system/stats'

export default {
  name: 'Index',
  components: { userAvatar, userInfo },
  data() {
    return {
      // 版本号
      version: '3.8.8',
      user: {},
      currentTime: '',
      weather: [],
      roleGroup: {},
      postGroup: {},
      status: '暂无MCN机构',
      statisticsItems: [
        {
          title: '发布内容',
          value: '0',
          icon: 'el-icon-video-camera-solid'
        },
        {
          title: '粉丝数',
          value: '0',
          icon: 'el-icon-s-marketing'
        },
        {
          title: '累计广告',
          value: '0',
          icon: 'el-icon-s-data'
        },
        {
          title: '总收益',
          value: '0',
          icon: 'el-icon-money'
        }
      ]
    }
  },
  created() {
    this.getUser()
    this.updateTime()
    setInterval(this.updateTime, 1000)
    this.initFansCharts()
  },
  mounted() {
    this.initFansCharts()
    this.initbodyCharts()
    this.getWeather()
    this.getContentsData()
    this.getlistDonations()
    this.getListAds()
    this.getListStats()
  },
  methods: {
    goTarget(href) {
      window.open(href, '_blank')
    },
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data
        this.roleGroup = response.roleGroup
        this.postGroup = response.postGroup
      })
    },
    updateTime() {
      const now = new Date()
      const year = now.getFullYear()
      const month = (now.getMonth() + 1).toString().padStart(2, '0')
      const date = now.getDate().toString().padStart(2, '0')
      const hours = now.getHours().toString().padStart(2, '0')
      const minutes = now.getMinutes().toString().padStart(2, '0')
      const seconds = now.getSeconds().toString().padStart(2, '0')
      this.currentTime = `${year}年${month}月${date}日 ${hours}:${minutes}:${seconds}`
    },
    getWeather() {
      axios.get('/weatherapi/api/weather/city/101070201')
        .then(response => {
          console.log('Weather data:', response.data) // 打印日志检查数据结构
          this.weather = response.data.data || [] // 确保 weather 赋值为一个数组
        })
        .catch(error => {
          console.error('Weather request error:', error)
        })
    },
    getTagType(status) {
      switch (status) {
        case '暂无MCN机构':
          return 'default' // 默认标签样式
        case '审核中':
          return 'success' // 成功状态样式
        case 'MCN签约博主':
          return 'info' // 信息状态样式
        default:
          return 'plain' // 平常状态样式
      }
    },
    initFansCharts() {
      var chartDom = document.getElementById('fansCharts')
      if (chartDom) {
        var myChart = echarts.init(chartDom)
        var option

        // 生成假数据
        const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        const youtubeFansData = [120, 150, 180, 220, 170, 200, 250] // YouTube 粉丝增长数
        const bilibiliFansData = [100, 130, 160, 200, 150, 180, 210] // bilibili 粉丝增长数
        const youtubeGrowthData = [10, 15, 20, 25, 20, 30, 35] // YouTube 每日增长
        const bilibiliGrowthData = [8, 12, 18, 22, 18, 25, 30] // bilibili 每日增长

        option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              crossStyle: {
                color: '#999'
              }
            }
          },
          toolbox: {
            feature: {
              restore: { show: true },
              saveAsImage: { show: true }
            }
          },
          legend: {
            data: ['YouTube 粉丝数', 'bilibili 粉丝数', 'YouTube 每日增长', 'bilibili 每日增长'],
            top: 'bottom'
          },
          xAxis: [
            {
              type: 'category',
              data: days,
              axisTick: {
                alignWithLabel: true
              }
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: '粉丝数',
              min: 0,
              max: 300,
              interval: 50,
              axisLabel: {
                formatter: '{value} 人'
              }
            },
            {
              type: 'value',
              name: '每日增长',
              min: 0,
              max: 50,
              interval: 10,
              axisLabel: {
                formatter: '{value} 人'
              },
              offset: 20 // 与左边的y轴分开一点
            }
          ],
          series: [
            {
              name: 'YouTube 粉丝数',
              type: 'bar',
              data: youtubeFansData
            },
            {
              name: 'bilibili 粉丝数',
              type: 'bar',
              data: bilibiliFansData
            },
            {
              name: 'YouTube 每日增长',
              type: 'line',
              yAxisIndex: 1,
              data: youtubeGrowthData
            },
            {
              name: 'bilibili 每日增长',
              type: 'line',
              yAxisIndex: 1,
              data: bilibiliGrowthData
            }
          ]
        }

        option && myChart.setOption(option)
      }
    },
    initbodyCharts() {
      var chartDom = document.getElementById('bodyCharts')
      if (chartDom) {
        var myChart = echarts.init(chartDom)
        var option

        setTimeout(function() {
          var option = {
            legend: {},
            tooltip: {
              trigger: 'axis',
              showContent: false
            },
            dataset: {
              source: [
                [
                  'week',
                  'Monday',
                  'Tuesday',
                  'Wednesday',
                  'Thursday',
                  'Friday',
                  'Saturday',
                  'Sunday'
                ],
                ['0-18 Years', 56, 82, 88, 70, 53, 85, 90],
                ['19-30 Years', 51, 51, 55, 53, 74, 69, 60],
                ['31-45 Years', 40, 62, 70, 36, 45, 33, 50],
                ['46+ Years', 25, 37, 41, 18, 34, 49, 55]
              ]
            },
            xAxis: { type: 'category' },
            yAxis: { gridIndex: 0 },
            grid: { top: '55%' },
            series: [
              {
                type: 'line',
                smooth: true,
                seriesLayoutBy: 'row',
                emphasis: { focus: 'series' }
              },
              {
                type: 'line',
                smooth: true,
                seriesLayoutBy: 'row',
                emphasis: { focus: 'series' }
              },
              {
                type: 'line',
                smooth: true,
                seriesLayoutBy: 'row',
                emphasis: { focus: 'series' }
              },
              {
                type: 'line',
                smooth: true,
                seriesLayoutBy: 'row',
                emphasis: { focus: 'series' }
              },
              {
                type: 'pie',
                id: 'pie',
                radius: '30%',
                center: ['50%', '25%'],
                emphasis: {
                  focus: 'self'
                },
                label: {
                  formatter: '{b}: {c} ({d}%)'
                },
                encode: {
                  itemName: 'week',
                  value: 'Monday', // 默认值，可以根据需要调整
                  tooltip: 'Monday' // 默认值，可以根据需要调整
                }
              }
            ]
          }

          myChart.on('updateAxisPointer', function(event) {
            const xAxisInfo = event.axesInfo[0]
            if (xAxisInfo) {
              const dimension = xAxisInfo.value
              myChart.setOption({
                series: {
                  id: 'pie',
                  label: {
                    formatter: '{b}: {@[' + dimension + ']} ({d}%)'
                  },
                  encode: {
                    value: dimension,
                    tooltip: dimension
                  }
                }
              })
            }
          })

          myChart.setOption(option)
        })
      }
    },
    getContentsData() {
      listContents_msg().then(response => {
        this.statisticsItems[0].value = response.total.toString()
      })
    },
    getlistDonations() {
      listDonations().then(response => {
        if (response.code === 200) {  // 检查请求是否成功
          const rows = response.rows
          const totalRevenueSum = rows.reduce((sum, row) => sum + row.totalRevenue, 0)
          this.statisticsItems[3].value = totalRevenueSum
        } else {
          console.log('查询失败:', response.msg)
        }
      }).catch(error => {
        console.error('请求出错:', error)
      })
    },
    getListAds() {
      listAds().then(response => {
        if (response.code === 200) {  // 检查请求是否成功
          const totalAdsSum = response.rows.length
          this.statisticsItems[2].value = totalAdsSum
        } else {
          console.log('查询失败:', response.msg)
        }
      }).catch(error => {
        console.error('请求出错:', error)
      })
    },
    getListStats() {
      listStats().then(response => {
        if (response.code === 200) {
          const totalStatsSum = response.rows.length
          this.statisticsItems[1].value = totalStatsSum
        } else {
          console.log('查询失败:', response.msg)
        }
      }).catch(error => {
        console.error('请求出错:', error)
      })
    }
  }
}
</script>

<style scoped lang="scss">
.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }

  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }

  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }
}

.statistics {
  margin-bottom: 20px;
}

.text-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
}

.title {
  font-size: 14px;
  color: #99a9bf;
}

.value {
  font-size: 24px;
  color: #f56c00;
  margin-top: 5px;
}

.icon {
  width: 32px;
  height: 32px;
}

.text-container {
  text-align: center;
}

.icon-text {
  display: flex;
  align-items: center; /* 使图标和文字在垂直方向上对齐 */
  justify-content: center; /* 使图标和文字在水平方向上居中对齐 */
  margin-bottom: 10px;
}

.icon {
  font-size: 24px;
  color: #3c1361;
  margin-right: 8px; /* 设置图标和文字之间的间距 */
}

.title {
  font-size: 14px;
  color: #333;
}

.value {
  font-size: 18px;
  color: #3c1361;
}
</style>

